<!-- 广告管理 -->
<template>
  <div>
    <!-- 查找 -->
    <el-space wrap>
      <el-select class="m-2" v-model="Advertising.status" placeholder="请选择广告的状态">
        <el-option v-for="item in refFreez" :key="item.value" :label="item.name" :value="item.value" />
      </el-select>
      <el-select class="m-2" v-model="Advertising.type" placeholder="请选择广告类型">
        <el-option v-for="item in refadTypeMap" :key="item.value" :label="item.name" :value="item.value" />
      </el-select>
      <el-button type="primary" :icon="Search" @click="handlesearch">查找</el-button>
      <el-button type="primary" :icon="Search" @click="handleradd" v-permission='"promotion:advert:create"'>添加</el-button>
    </el-space>

    <!-- 表格 -->
    <div style="margin-top: 20px">
      <el-table :data="reftabledata.list" style="width: 100%" border>
        <el-table-column prop="id" label="广告ID" align="center" />
        <el-table-column prop="title" label="广告标题" align="center" />
        <el-table-column label="广告图片" align="center">
          <template #default="scope">
            <el-popover placement="right" width="auto" v-if="scope.row.type != 6 && scope.row.type != 9">
              <template #reference>
                <img :src="scope.row.imgUrl" mode="heightFix" style="height: 100px; vertical-align: middle" />
              </template>
              <template #default>
                <img :src="scope.row.imgUrl" mode="heightFix" style="height: 150px" />
              </template>
            </el-popover>
            <el-tag v-else>此类型无需图片</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="广告类型" align="center">
          <template #default="scope">
            <template v-for="item in refadTypeMap">
              <el-tag v-if="scope.row.type == item.value" :key="item.value">{{
              item.name
              }}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="广告状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status == 0 ? 'danger' : 'success'">{{
            scope.row.status == 0 ? "冻结" : "激活"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关联类型" align="center">
          <template #default="scope">
            <template v-for="item in refadUnionTypeMap">
              <el-tag type="warning" v-if="scope.row.unionType == item.value" :key="item.value">{{ item.name }}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="unionValue" label="关联值[ID]" align="center" />
        <el-table-column prop="gmtCreate" label="创建时间" align="center">
          <template #default="scope">
            <span>{{ new Date(scope.row.gmtCreate).creationTime() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" align="center" width="200%">
          <template #default="scope">
            <el-button type="primary" plain @click="handleedit(scope.row)" v-permission='"promotion:advert:edit"'>编辑</el-button>
            <el-button type="danger" plain @click="handledelete(scope.row)"  v-permission='"promotion:advert:delete"'>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <paging-list @Change="giterList" :listdata="listdata"></paging-list>

    <!-- 弹出框 -->
    <el-dialog destroy-on-close v-model="refdialogFormVisible" :title="title">
      <el-form :model="refform" :rules="refrules" status-icon ref="ruleFormRef">
        <el-form-item label="广告标题" prop="title">
          <el-input v-model="refform.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="广告类型" prop="type">
          <el-select v-model="refform.type" @change="handlerformType" placeholder="请选择广告类型">
            <el-option v-for="item in refadTypeMap.slice(0, 6)" :key="item.value" :label="item.name"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="广告图片" class="item_from" id="upload" v-if="
          refadTypeMap.find((item) => item.value == refform.type)?.picRequire
        " :style="{ background: refform.color }">
          <el-upload class="avatar-uploader" action="/upload/admin" :headers="headers" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="refform.imgUrl" :src="refform.imgUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="广告状态" prop="status">
          <el-switch v-model="refform.status" :active-value="1" :inactive-value="0" active-color="#13ce66" />
        </el-form-item>
        <el-form-item label="关联类型" prop="unionType">
          <el-select v-model="refform.unionType" @change="refform.unionValue = ''" :placeholder="
            refform.type == '' ? '请先选择广告类型' : '请先选择广告类型'
          ">
            <el-option v-for="(item, index) in refadUnionTypeMap" :disabled="handleformUnionType(item.value)"
              :key="index" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品" prop="unionValue" v-if="refform.unionType == 1" :rules="refunionRule.goods"
          label-width="80px">
          <el-cascader :options="refadTypeInfo.goods" v-model="refform.unionValue" :props="refgoodsProps" clearable
            placeholder="关联至商品" />
        </el-form-item>
        <el-form-item v-else-if="refform.unionType == 2" label="类目" prop="unionValue" :rules="refunionRule.category"
          label-width="80px">
          <el-cascader :options="refadTypeInfo.category" v-model="refform.unionValue" :props="refcategoryProps"
            clearable placeholder="关联至类目" />
        </el-form-item>
        <el-form-item v-else-if="refform.unionType == 3" label="关键字" prop="unionValue" :rules="refunionRule.keyword"
          label-width="80px">
          <el-input v-model.trim="refform.unionValue" placeholder='点击广告后,用户将得到"此关键字"的商品信息' autocomplete="off" />
        </el-form-item>
        <el-form-item v-else-if="refform.unionType == 4" label="功能页面" prop="unionValue" :rules="refunionRule.fun">
          <el-select v-model="refform.unionValue" placeholder="请选择一个功能页面">
            <el-option v-for="(item, index) in refadTypeInfo.functionPages" :key="index" :label="item.name"
              :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refdialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handlesubmitForm(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { post } from "@/utils/request";
import { Search, Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Pageadvertisement } from "#/index";
import Cookies from "js-cookie";
import type { UploadProps, FormInstance, FormRules } from "element-plus";
import PagingList from "../../components/specialfunctions/PagingList.vue";
import { theColorFn } from "@/utils/theColor";

let backgint = ref("");
let Advertising = reactive({
  type: "",
  status: null,
});
//分页数据
let listdata = reactive(new Pageadvertisement());
// 分页
const giterList = (e: {
  page: number;
  limit: number;
  total: number;
  flog: { valueOf: () => boolean };
  targetAdminId?: undefined;
}) => {
  //获取下一页的数据并赋值
  listdata = e;
  handleradvertisement();
};
// 选择的广告类型
const refFreez = reactive([
  { value: 0, name: "冻结" },
  { value: 1, name: "激活" },
  { value: "", name: "全部" },
]);
//判断title
let title = ref("");
// 获取token
const headers = reactive({ adminToken: Cookies.get("token") });
const ruleFormRef = ref<FormInstance>();
//控制图片显示隐藏
// let refselect = ref(false)
// 优惠类目定义规则
const refcategoryProps = reactive({
  label: "title",
  children: "childrenList",
  value: "id",
  emitPath: false,
});
// 商品定义规则
const refgoodsProps = reactive({ value: "id", emitPath: false });
// 关联类型信息
let refadTypeInfo = reactive({
  goods: [] as string[],
  category: [] as string[],
  functionPages: [
    { value: "/pages/product/groupshop", name: "团购列表" },
    { value: "/pages/couponst", name: "优惠券列表" },
  ],
});
//表格数据
const reftabledata = reactive({ list: [] as string[] });
//广告类目
const refadTypeMap = reactive([
  { value: 1, unionTypes: [1, 2, 3, 4], picRequire: true, name: "轮播" },
  { value: 2, unionTypes: [2], picRequire: true, name: "分类精选" },
  { value: 3, unionTypes: [1, 2, 3, 4], picRequire: true, name: "横幅" },
  {
    value: 4,
    unionTypes: [1, 2, 3, 4],
    picRequire: true,
    name: "首页轮播下5按钮",
  },
  { value: 6, unionTypes: [1, 2, 3, 4], picRequire: false, name: "广告" },
  { value: 9, unionTypes: [1], picRequire: false, name: "商品推荐" },
]);
//关联类型
const refadUnionTypeMap = reactive([
  { value: 1, name: "商品" },
  { value: 2, name: "类目" },
  { value: 3, name: "关键字" },
  { value: 4, name: "功能页面" },
]); //关联类型
//控制弹出框的显示和隐藏
const refdialogFormVisible = ref(false);
//表单绑定数据
const refform: Typedvertisement = reactive({
  title: "",
  type: "",
  imgUrl: "",
  color: "",
  status: 0,
  unionType: "",
  unionValue: "",
  adId: "",
});
//表单验证
const refrules = reactive({
  title: [{ required: true, message: "请输入广告标题", trigger: "blur" }],
  type: [{ required: true, message: "请选择广告类型", trigger: "blur" }],
  status: [{ required: true, message: "请选择广告状态", trigger: "blur" }],
  unionType: [{ required: true, message: "请选择关联类型", trigger: "blur" }],
}); //表单验证
// 关联类型验证
const refunionRule = reactive({
  goods: [{ required: true, message: "请选择商品", trigger: "change" }],
  category: [{ required: true, message: "请选择类目", trigger: "change" }],
  keyword: [
    {
      required: true,
      message: "请关联一个(商品,类目,页面等具体值)",
      trigger: "blur",
    },
  ],
  fun: [{ required: true, message: "请选择功能页面", trigger: "change" }],
}); // 关联类型验证
//禁用关联的数组
let refunionTypeVal = reactive([] as number[]);

let refdataind = { ...refform }; //添加成功后需要清空的数据

// 图片上传
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (200 == response.errno) {
    refform.imgUrl = response.url; // 得到上传图片成功的路径
    theColorFn(refform.imgUrl, (callback: string) => {
      refform.color = callback;
    }); // 计算得到图片平均色
    handleradvertisement();
  }
  // refform.imgUrl = response.url;
};
// 图片的格式验证
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

/**
 * 初始化表格数据
 */
function handleradvertisement() {
  let data = {
    _gp: "admin.advert",
    _mt: "list",
    type: listdata.type,
    pageNo: listdata.page,
    limit: listdata.limit,
    status: listdata.status,
  };
  post(data).then((res) => {
    let { data, errno, errmsg } = res;
    reftabledata.list.length = 0;
    reftabledata.list.push(...data.items);
    listdata.total = data.total;
  });
}
handleradvertisement();

/**
 * 关联列表 商品信息
 */
function handleCommodity() {
  let data = {
    _gp: "admin.product",
    _mt: "getSpuBigTree",
  };
  post(data).then((res) => {
    let { data, errno, errmsg } = res;
    refadTypeInfo.goods.length = 0;
    refadTypeInfo.goods.push(...res.data);
  });
}

/**
 * 类目信息
 */
function handleTypeCategory() {
  if (refadTypeInfo.category.length == 0) {
    let data = {
      _gp: "admin.category",
      _mt: "categoryTree",
    };
    post(data).then((res) => {
      let { data, errno, errmsg } = res;
      refadTypeInfo.category.length = 0;
      refadTypeInfo.category.push(...res.data);
    });
  }
}

/**
 * 打开弹出框
 */
function handleradd() {
  handleCommodity();
  handleTypeCategory();
  title.value = "创建";
  refdialogFormVisible.value = true;
  Object.assign(refform, refdataind);
}
/**
 * 打开编辑框并赋值
 */
function handleedit(row: { id: string; color: string }) {
  if (!isNaN(row.unionValue)) {
    row.unionValue = parseInt(row.unionValue);
  }
  handleCommodity();
  handleTypeCategory();
  title.value = "编辑";
  refdialogFormVisible.value = true;
  refform.adId = row.id;
  Object.assign(refform, row);
}
/**
 * 创建和编辑的确认
 */
const handlesubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      handleedittable();
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * 创建和编辑判断
 */
function handleedittable() {
  refform.imgUrl = "" ? refform.imgUrl : "";
  if (title.value == "创建") {
    let data = {
      _gp: "admin.advert",
      _mt: "create",
      ...refform,
    };
    post(data).then((res) => {
      let { errmsg, errno } = res;
      if (200 == errno) {
        handleradvertisement();
        refdialogFormVisible.value = false;
        ElMessage.success("创建成功");
      }
    });
  } else {
    if (refform.type == 6 || refform.type == 9) {
      refform.imgUrl = "";
      refform.color = "";
    }
    let data = {
      _gp: "admin.advert",
      _mt: "edit",
      ...refform,
    };
    post(data).then((res) => {
      let { errmsg, errno } = res;
      if (200 == errno) {
        handleradvertisement();
        refdialogFormVisible.value = false;
        ElMessage.success("编辑成功");
      }
    });
  }
}

/**
 * 删除表格信息
 */
function handledelete(row: { id: string; type: number }) {
  ElMessageBox.confirm("代理将永久删除该文件", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let data = {
        _gp: "admin.advert",
        _mt: "delete",
        type: row.type,
        adId: row.id,
      };
      post(data).then((res) => {
        let { errno, errmsg } = res;
        if (200 == errno) {
          handleradvertisement();
          ElMessage({
            type: "success",
            message: "删除成功！",
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Delete canceled",
      });
    });
}

/**
 * 禁用关联选项
 */
function handlerformType(e: number) {
  // refadTypeMap.forEach((item)=>{
  //   if(item.value===e){
  //     refselect.value = item.picRequire
  //   }
  // })
  refunionTypeVal = refadTypeMap.filter((item) => item.value == e)[0]
    .unionTypes;
  refform.unionType = ""; //切换后重新赋值关联类型选择
}
/**
 * 禁用关联选项
 */
function handleformUnionType(value: number) {
  for (const item of refunionTypeVal) {
    if (item == value) {
      return false;
    }
  }
  return true;
}

/**
 * 搜索表格信息
 */
function handlesearch() {
  listdata.status = Advertising.status;
  listdata.type = Advertising.type;
  handleradvertisement();
}
</script>

<style lang="less" scoped>
.item_from {
  margin-left: 10px;
}
</style>

<style>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
